//
// Created by gnehcnij on 2021/11/3.
//

#include <stdio.h>
#include <stdlib.h>
#include "../include/commonutils.h"

void out_of_memory() {
    printf("Error: out of memory\n");
    exit(1);
}

int strlenChar(const char *z) {
    int n = 0;
    while (*z) {
        if ((0xc0 & *(z++)) != 0x80) n++;
    }
    return n;
}

void print_dashes(FILE *out, int N) {
    const char zDash[] = "--------------------------------------------------";
    const int nDash = sizeof(zDash) - 1;
    while (N > nDash) {
        fputs(zDash, out);
        N -= nDash;
    }
    fprintf(out, "%.*s", N, zDash);
}

void print_row_separator(
        FILE *out,
        int *actualWidth,
        int nArg,
        const char *zSep
) {
    int i;
    if (nArg > 0) {
        fputs(zSep, out);
        print_dashes(out, actualWidth[0] + 2);
        for (i = 1; i < nArg; i++) {
            fputs(zSep, out);
            print_dashes(out, actualWidth[i] + 2);
        }
        printf("%s", zSep);
    }
    fputs("\n", out);
}

void utf8_width_print(FILE *pOut, int w, const char *zUtf) {
    int i;
    int n;
    int aw = w < 0 ? -w : w;
    for (i = n = 0; zUtf[i]; i++) {
        if ((zUtf[i] & 0xc0) != 0x80) {
            n++;
            if (n == aw) {
                do { i++; } while ((zUtf[i] & 0xc0) == 0x80);
                break;
            }
        }
    }
    if (n >= aw) {
        fprintf(pOut, "%.*s", i, zUtf);
    } else if (w < 0) {
        fprintf(pOut, "%*s%s", aw - n, "", zUtf);
    } else {
        fprintf(pOut, "%s%*s", zUtf, aw - n, "");
    }
}

int strlen30(const char *z) {
    const char *z2 = z;
    while (*z2) { z2++; }
    return 0x3fffffff & (int) (z2 - z);
}